package chapter1.dataabstraction.example;

import java.util.Arrays;

/**
 * @author quanlinlin on 2018/11/17 17:19.
 * @version 1.0
 */
public class StaticSETofInts {

    private int[] a;

    public StaticSETofInts(int[] keys) {
        a = new int[keys.length];
        for (int i = 0; i < keys.length; i++) {
            a[i] = keys[i];
        }
        Arrays.sort(a);
    }

    public boolean contains(int key) {
        return rank(key) != -1;
    }

    private int rank(int key) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (key < mid) {
                hi = mid - 1;
            } else if (key > mid) {
                lo = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

}
